package com.example.projectmanagement.controller.study;

import com.example.projectmanagement.dto.study.UserLessonProgressDto;
import com.example.projectmanagement.model.study.UserLessonProgress;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.service.study.StudyProgressService;
import com.example.projectmanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/study/progress")
@CrossOrigin
public class StudyProgressController {

    @Autowired
    private StudyProgressService progressService;
    
    @Autowired
    private UserService userService;

    /**
     * 开始学习课时
     */
    @PostMapping("/lessons/{lessonId}/start")
    public ResponseEntity<UserLessonProgress> startLesson(@PathVariable Long lessonId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            UserLessonProgress progress = progressService.startLesson(userOpt.get(), lessonId);
            return ResponseEntity.ok(progress);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 更新课时学习进度
     */
    @PutMapping("/lessons/{lessonId}/update")
    public ResponseEntity<UserLessonProgress> updateLessonProgress(
            @PathVariable Long lessonId,
            @RequestParam Integer viewedDuration) {
        
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            UserLessonProgress progress = progressService.updateLessonProgress(userOpt.get(), lessonId, viewedDuration);
            return ResponseEntity.ok(progress);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 完成课时学习
     */
    @PostMapping("/lessons/{lessonId}/complete")
    public ResponseEntity<UserLessonProgress> completeLesson(@PathVariable Long lessonId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            UserLessonProgress progress = progressService.completeLesson(userOpt.get(), lessonId);
            return ResponseEntity.ok(progress);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取用户课时学习进度
     */
    @GetMapping("/lessons/{lessonId}")
    public ResponseEntity<UserLessonProgress> getLessonProgress(@PathVariable Long lessonId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<UserLessonProgress> progress = progressService.getLessonProgress(userOpt.get(), lessonId);
        return progress.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * 获取用户课程的所有课时进度
     */
    @GetMapping("/courses/{courseId}")
    public ResponseEntity<List<UserLessonProgressDto>> getCourseProgress(@PathVariable Long courseId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        List<UserLessonProgress> progressList = progressService.getCourseProgress(userOpt.get(), courseId);
        List<UserLessonProgressDto> progressDtos = progressList.stream()
                .map(this::convertToProgressDto)
                .collect(Collectors.toList());
        
        return ResponseEntity.ok(progressDtos);
    }
    
    /**
     * 获取用户课程的总体进度信息
     */
    @GetMapping("/courses/{courseId}/overview")
    public ResponseEntity<Map<String, Object>> getCourseProgressOverview(@PathVariable Long courseId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        Map<String, Object> progressOverview = progressService.getCourseOverallProgress(userOpt.get(), courseId);
        return ResponseEntity.ok(progressOverview);
    }

    /**
     * 重置课时进度
     */
    @DeleteMapping("/lessons/{lessonId}/reset")
    public ResponseEntity<Void> resetLessonProgress(@PathVariable Long lessonId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            progressService.resetLessonProgress(userOpt.get(), lessonId);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取当前认证用户的ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();
            return userService.getUserByUsername(username).map(User::getId).orElse(null);
        }
        return null;
    }

    /**
     * 转换UserLessonProgress到UserLessonProgressDto
     */
    private UserLessonProgressDto convertToProgressDto(UserLessonProgress progress) {
        UserLessonProgressDto dto = new UserLessonProgressDto();
        dto.setId(progress.getId());
        if (progress.getUser() != null) {
            dto.setUserId(progress.getUser().getId());
        }
        if (progress.getLesson() != null) {
            dto.setLessonId(progress.getLesson().getId());
            dto.setLessonTitle(progress.getLesson().getTitle());
        }
        dto.setStatus(progress.getStatus());
        dto.setViewedDuration(progress.getViewedDuration());
        dto.setTotalDuration(progress.getTotalDuration());
        dto.setStartTime(progress.getStartTime());
        dto.setLastAccessTime(progress.getLastAccessTime());
        dto.setCompletionTime(progress.getCompletionTime());
        return dto;
    }
}